﻿using System.Collections.Generic;
#if DOTween
using DG.Tweening;
#endif
#if MeshPro
using TMPro;
#endif
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 负责显示血条，内置对象池
    /// </summary>
    public class BloodSpriteMa : BaseMono
    {
        private Queue<GameObject> objPool = new Queue<GameObject>();
        private Dictionary<int, GameObject> objUsePool = new Dictionary<int, GameObject>(); //正在使用的过程

        public GameObject bloodPrefab;

        public float endY = 0.5f;
        public float endDurationY = 1f;

        protected void Awake()
        {
            eventc.RegisterEvent<BloodBounceArgs>(BloodBounceArgs.EventId, OnShowBlood);
        }

        protected void OnEnable()
        {
        }

        public void OnShowBlood(BloodBounceArgs args)
        {
            int count = objPool.Count;
            GameObject origin = args.go;
            GameObject go = null;
            if (count > 0)
            {
                go = objPool.Dequeue();
            }
            else
            {
                go = CreateBlood();
            }

            objUsePool.Add(go.GetInstanceID(), go);
            go.transform.position = origin.transform.position;
            go.gameObject.SetActive(true);
            ITextMeshPro pro = go.GetComponent<ITextMeshPro>();
            pro.text = args.text;

            Vector3 endVector3 = origin.transform.position;
            endVector3.y += endY;
#if DOTween
            //添加动画
            Tweener t = go.transform.DOMove(endVector3, endDurationY).OnComplete(() =>
            {
                go.SetActive(false);
                objUsePool.Remove(go.GetInstanceID());
                objPool.Enqueue(go);
                //Debug.Log("结束，放回poll里面");
            });

            t.Play();
#endif
        }

        public GameObject CreateBlood()
        {
            GameObject go = null;

            if (bloodPrefab != null)
            {
                go = Instantiate(bloodPrefab);
            }
            else
            {
                go = new GameObject();
                go.name = "blood";
#if MeshPro
                var textMesh = go.AddComponent<TextMeshPro>();
                MeshRenderer r = go.GetComponent<MeshRenderer>();
                r.sortingLayerName = DefineLayerMask.Effect;
                //textMesh.sortingLayerID = DefineLayerMask.IntEffect;
                textMesh.fontSize = 4;
                textMesh.alignment = TextAlignmentOptions.Center;
                textMesh.autoSizeTextContainer = true;
#endif
            }

            return go;
        }
    }
}